package com.welink.cmp.gatewayimpl.metadata;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.welink.cmp.convertor.GenericConvertor;
import com.welink.cmp.dao.metadata.EipDaoService;
import com.welink.cmp.dao.metadata.SwitchDaoService;
import com.welink.cmp.dao.metadata.dataobject.EipDO;
import com.welink.cmp.dao.metadata.dataobject.SwitchDO;
import com.welink.cmp.domain.metadata.Eip;
import com.welink.cmp.domain.metadata.Switch;
import com.welink.cmp.domain.metadata.gateway.IEipGateway;
import com.welink.cmp.domain.metadata.gateway.ISwitchGateway;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 交换机 Gateway 实现类
 */
@Component
@Primary
@Slf4j
public class EipGatewayImpl implements IEipGateway {

    @Autowired
    private EipDaoService eipDaoService;


    /**
     * @param eipList
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean saveOrUpdateBatchByIp(List<Eip> eipList) {
        //过滤全部 SN
        final List<String> allIpList = eipList.stream().map(Eip::getIp).collect(Collectors.toList());
        LambdaQueryWrapper<EipDO> queryWrapper = Wrappers.lambdaQuery(EipDO.class);
        queryWrapper.select(EipDO::getIp).in(EipDO::getIp,allIpList);
        final List<EipDO> existEipList = eipDaoService.list(queryWrapper);
        // 已存在的记录 SN-ID
        final Map<String, Long> existEipMap = existEipList.stream().collect(Collectors.toMap(EipDO::getIp, EipDO::getId));
        eipList.forEach(eipDo -> {
            final Long eipId = existEipMap.get(eipDo.getIp());
            if ( eipId !=null){
                eipDo.setId(eipId);
            }
        });
        List<EipDO> allSwitchDoList = GenericConvertor.toDOList(eipList, EipDO.class);
        // 批量更新
        final boolean rst = eipDaoService.saveOrUpdateBatch(allSwitchDoList);
        log.info("根据 Sn 批量更新或插入交换机[{}]，更新Sn记录{},全部Sn{} ",rst,existEipMap,eipList);
        return null;
    }


}
